package com.jiayou.activity

import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.hutool.core.util.RandomUtil
import cn.hutool.http.HttpRequest
import cn.hutool.json.JSONUtil
import com.jiayou.R
import com.jiayou.activity.adapter.ChatMessage
import com.jiayou.activity.adapter.Message
import com.jiayou.activity.adapter.MessageAdapter
import com.jiayou.im.entity.Chat
import com.jiayou.message.ChannelMessage
import com.jiayou.message.TextMessage
import com.jiayou.message.type.DataType
import com.jiayou.tool.AndroidTool
import com.jiayou.tool.SerializableTool
import kotlinx.android.synthetic.main.activity_chat.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.chat_tab.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.time.LocalDateTime
import java.util.*
import kotlin.collections.ArrayList
import kotlin.concurrent.thread

class ChatActivity : AppCompatActivity(), View.OnClickListener {
    private val list = ArrayList<ChatMessage>()
    private val me: String = MainActivity.ID    //自己的id
    private lateinit var id: String   //对方的id
    private lateinit var messageAdapter: RecyclerView.Adapter<MessageAdapter.MessageViewHolder>
    private val properties = Properties()
    lateinit var uri: String
    private var client = MainActivity.client

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)
        AndroidTool.fullScreen(this)
        id = intent.getStringExtra("id").toString()
        user_name.text = intent.getStringExtra("name").toString()
        back.setOnClickListener(this)
        send_message.setOnClickListener(this)

        properties.load(application.assets.open("im.properties"))
        uri = properties["im.uri"].toString() + ":" + properties["im.port"].toString()
        getMessage()
        println("对方的id:${id}    我的id:$me")
    }

    private fun initClient() {
        MainActivity.client.adapter = messageAdapter
        MainActivity.client.recyclerview = messagslist
        MainActivity.client.who = id
        MainActivity.client.list = list
    }

    private fun destroyClient() {
        MainActivity.client.adapter = null
        MainActivity.client.recyclerview = null
        MainActivity.client.who = null
        MainActivity.client.list = null
    }

    private fun getMessage() {
        thread {
            runBlocking {
                val parse = JSONUtil.parseObj(
                    HttpRequest.get("http://$uri/im/chat/getMessage")
                        .form(
                            mapOf(
                                "id1" to me,
                                "id2" to id
                            )
                        )
                        .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                        .execute()
                        .body()
                )

                JSONUtil.parseArray(parse["data"]).forEach {
                    list.add(JSONUtil.toBean(JSONUtil.parseObj(it), ChatMessage::class.java))
                }
                list.reverse()
                withContext(Dispatchers.Main) {
                    messageAdapter = MessageAdapter(this@ChatActivity, id, list)
                    messageAdapter.setHasStableIds(true)
                    messagslist.adapter = messageAdapter

                    val manager = LinearLayoutManager(this@ChatActivity)
                    manager.orientation = LinearLayoutManager.VERTICAL
                    messagslist.layoutManager = manager
                    messagslist.scrollToPosition(list.size - 1)
                    Toast.makeText(this@ChatActivity, "获取聊天信成功！", Toast.LENGTH_SHORT).show()
                }
                initClient()
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.back -> {
                destroyClient()
                finish()
            }
            R.id.send_message -> {
                sendMessage()
                println("开始")
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun sendMessage() {
        thread {
            runBlocking {
                if (!input_message.text.isEmpty()) {
                    val message = TextMessage(
                        from = me,
                        to = id,
                        text = input_message.text.toString(),
                        time = LocalDateTime.now()
                    )
                    val objectToByteArray = SerializableTool.ObjectToByteArray(message)
                    client.server.channel().writeAndFlush(
                        ChannelMessage(
                            objectToByteArray.size,
                            DataType.TEXT,
                            objectToByteArray
                        )
                    )
                    list.add(
                        ChatMessage(
                            1,
                            me,
                            id,
                            input_message.text.toString(),
                            LocalDateTime.now()
                        )
                    )
                    withContext(Dispatchers.Main) {
                        messageAdapter.notifyItemInserted(list.size - 1)
                        messagslist.scrollToPosition(list.size - 1)
                        Unit
                    }
                    input_message.setText("")
                }

            }
        }
    }

    override fun onBackPressed() {
        destroyClient()
        finish()
    }

}